<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Vue,">





  <link rel="alternate" href="/atom.xml" title="YauCheun's Blog" type="application/atom+xml">






<meta name="description" content="1.前言每当被问到Vue数据双向绑定原理的时候，大家可能都会脱口而出：Vue内部通过Object.defineProperty方法属性拦截的方式，把data对象里每个数据的读写转化成getter/setter，当数据变化时通知视图更新。虽然一句话把大概原理概括了，但是其内部的实现方式还是值得深究的，本文就以通俗易懂的方式剖析Vue内部双向绑定原理的实现过程。">
<meta name="keywords" content="Vue">
<meta property="og:type" content="article">
<meta property="og:title" content="vue2.x-理解双向绑定">
<meta property="og:url" content="http://yoursite.com/2020/12/08/vue2.x-理解双向绑定/index.html">
<meta property="og:site_name" content="YauCheun&#39;s Blog">
<meta property="og:description" content="1.前言每当被问到Vue数据双向绑定原理的时候，大家可能都会脱口而出：Vue内部通过Object.defineProperty方法属性拦截的方式，把data对象里每个数据的读写转化成getter/setter，当数据变化时通知视图更新。虽然一句话把大概原理概括了，但是其内部的实现方式还是值得深究的，本文就以通俗易懂的方式剖析Vue内部双向绑定原理的实现过程。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/24590971-2a4a5aec70d3fdeb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/24590971-ad648c8485f7f2a2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2020-12-21T13:54:10.580Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="vue2.x-理解双向绑定">
<meta name="twitter:description" content="1.前言每当被问到Vue数据双向绑定原理的时候，大家可能都会脱口而出：Vue内部通过Object.defineProperty方法属性拦截的方式，把data对象里每个数据的读写转化成getter/setter，当数据变化时通知视图更新。虽然一句话把大概原理概括了，但是其内部的实现方式还是值得深究的，本文就以通俗易懂的方式剖析Vue内部双向绑定原理的实现过程。">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/24590971-2a4a5aec70d3fdeb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">
<style>
    .pace .pace-progress {
        background: #1E92FB; /*进度条颜色*/
        height: 3px;
    }
    .pace .pace-progress-inner {
         box-shadow: 0 0 10px #1E92FB, 0 0 5px     #1E92FB; /*阴影颜色*/
    }
    .pace .pace-activity {
        border-top-color: #1E92FB;    /*上边框颜色*/
        border-left-color: #1E92FB;    /*左边框颜色*/
    }
</style>



  <link rel="canonical" href="http://yoursite.com/2020/12/08/vue2.x-理解双向绑定/">





  <title>vue2.x-理解双向绑定 | YauCheun's Blog</title>
  








 
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
  

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">YauCheun's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Thoughts, stories and ideas</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/12/08/vue2.x-理解双向绑定/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="YauCheun">
      <meta itemprop="description" content>
      <meta itemprop="image" content="http://tva2.sinaimg.cn/crop.0.0.768.768.1024/6cc1c2cfjw8eh3kv8yvs9j20lc0lcdgl.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="YauCheun's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">vue2.x-理解双向绑定</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-08T20:20:01+08:00">
                2020-12-08
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Vue/" itemprop="url" rel="index">
                    <span itemprop="name">Vue</span>
                  </a>
                </span>

                
                
              
            </span>
          



          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="1-前言"><a href="#1-前言" class="headerlink" title="1.前言"></a>1.前言</h3><p>每当被问到Vue数据双向绑定原理的时候，大家可能都会脱口而出：Vue内部通过Object.defineProperty方法属性拦截的方式，把data对象里每个数据的读写转化成getter/setter，当数据变化时通知视图更新。虽然一句话把大概原理概括了，但是其内部的实现方式还是值得深究的，本文就以通俗易懂的方式剖析Vue内部双向绑定原理的实现过程。</p>
<a id="more"></a>

<h3 id="2-思路分析"><a href="#2-思路分析" class="headerlink" title="2.思路分析"></a>2.思路分析</h3><p>所谓MVVM数据双向绑定，即主要是：数据变化更新视图，视图变化更新数据。如下图：</p>
<p><img src="https://upload-images.jianshu.io/upload_images/24590971-2a4a5aec70d3fdeb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></p>
<p>也就是说：</p>
<ul>
<li>输入框内容变化时，data 中的数据同步变化。即 view =&gt; model 的变化。</li>
<li>data 中的数据变化时，文本节点的内容同步变化。即 model =&gt; view 的变化。</li>
</ul>
<h3 id="3-原理"><a href="#3-原理" class="headerlink" title="3.原理"></a>3.原理</h3><pre><code>1.vue 双向数据绑定是通过 数据劫持 结合 发布订阅模式的方式来实现的， 也就是说数据和视图同步，数据发生变化，视图跟着变化，视图变化，数据也随之发生改变；

2.核心：关于VUE双向数据绑定，其核心是 Object.defineProperty()方法；

3.介绍一下Object.defineProperty()方法
    Object.defineProperty(obj, prop, descriptor) ，这个语法内有三个参数，分别为obj（要定义其上属性的对象），prop （要定义或修改的属性），descriptor （具体的改变方法）
    简单地说，就是用这个方法来定义一个值。当调用时我们使用了它里面的get方法，当我们给这个属性赋值时，又用到了它里面的set方法</code></pre><p>详情可参考 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty" target="_blank" rel="noopener">MDN|Object.defineProperty()</a></p>
<h3 id="4-具体实现"><a href="#4-具体实现" class="headerlink" title="4.具体实现"></a>4.具体实现</h3><h4 id="1-实现效果"><a href="#1-实现效果" class="headerlink" title="1.实现效果"></a>1.实现效果</h4><p>先来看一下vue双向数据绑定是如何进行的，以便我们确定好思考方向</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"app"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span>  <span class="attr">v-model</span>=<span class="string">"text"</span>&gt;</span>&#123;&#123;text&#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建一个vue实例</span></span><br><span class="line">  <span class="keyword">var</span> vm=<span class="keyword">new</span> Vue(&#123;</span><br><span class="line">        el:<span class="string">'app'</span>,</span><br><span class="line">        data:&#123;</span><br><span class="line">            text:<span class="string">'hello world'</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br></pre></td></tr></table></figure>

<h4 id="2-任务拆分"><a href="#2-任务拆分" class="headerlink" title="2.任务拆分"></a>2.任务拆分</h4><p>拆分任务可以让我们的思路更加清晰：<br>    （1）将vue中的data中的内容绑定到输入文本框和文本节点中<br>    （2）当文本框的内容改变时，vue实例中的data也同时发生改变<br>    （3）当data中的内容发生改变时，输入框及文本节点的内容也发生变化</p>
<h4 id="3-分布执行任务"><a href="#3-分布执行任务" class="headerlink" title="3.分布执行任务"></a>3.分布执行任务</h4><h5 id="1-任务1-绑定data到view"><a href="#1-任务1-绑定data到view" class="headerlink" title="1.任务1-绑定data到view"></a>1.任务1-绑定data到view</h5><p>我们先了解一下 <code>DocuemntFragment（碎片化文档）</code>这个概念，你可以把他认为一个dom节点收容器，当你创造了10个节点，当每个节点都插入到文档当中都会引发一次浏览器的回流，也就是说浏览器要回流10次，十分消耗资源。而使用碎片化文档，也就是说我把10个节点都先放入到一个容器当中，最后我再把容器直接插入到文档就可以了！浏览器只回流了1次。<br>    注意：还有一个很重要的特性是，如果使用appendChid方法将原dom树中的节点添加到DocumentFragment中时，会删除原来的节点。<br>利用<code>DocuemntFragment</code>的这个特性，可以通过<code>while</code>循环将需要绑定区域的内容添加到碎片化文档中</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//碎片化文档，遍历app所有子元素，调用编译函数更新model</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">nodeTofragment</span>(<span class="params">node,vm</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">let</span> fragment=<span class="built_in">document</span>.createDocumentFragment()</span><br><span class="line">      <span class="keyword">let</span> child</span><br><span class="line">      <span class="keyword">while</span>(child=node.firstChild)&#123;</span><br><span class="line">          fragment.appendChild(child)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> fragment</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p>接下来就需要将data中的数据分别绑定到<code>input</code> 框上和文本节点。目前闲置我们已经获取到了<code>div</code>的所有子节点了，就在<code>DocumentFragment</code>里面，然后对每一个节点进行处理，看是不是有跟vm实例中有关联的内容，如果有，修改这个节点的内容。然后重新添加入<code>DocumentFragment</code>中。</p>
<p>首先，我们写一个处理每一个节点的函数，如果有<code>input</code>绑定<code>v-model</code>属性或者有的文本节点出现，就进行内容替换，替换为vm实例中的data中的内容。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 编译函数，把data数据更新给model</span></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">compile</span>(<span class="params">node,vm</span>) </span>&#123;</span><br><span class="line">     <span class="keyword">let</span> attr = node.attributes</span><br><span class="line">     <span class="keyword">if</span>(node.nodeType===<span class="number">1</span>)&#123;</span><br><span class="line">         <span class="keyword">for</span>(<span class="keyword">let</span> i=<span class="number">0</span>;i&lt;attr.length;i++)&#123;</span><br><span class="line">             <span class="keyword">if</span>(attr[i].nodeName==<span class="string">'v-model'</span>)&#123;</span><br><span class="line">                 <span class="keyword">let</span> name = attr[i].nodeValue</span><br><span class="line">                 node.value=vm.data[name]</span><br><span class="line">                 node.removeAttribute(<span class="string">'v-model'</span>)</span><br><span class="line">             &#125;</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="keyword">let</span> reg=<span class="regexp">/\&#123;\&#123;(.*)\&#125;\&#125;/</span></span><br><span class="line">     <span class="keyword">if</span>(node.nodeType===<span class="number">3</span>)&#123;</span><br><span class="line">         <span class="keyword">if</span>(reg.test(node.nodeValue))&#123;</span><br><span class="line">             <span class="keyword">let</span> name = <span class="built_in">RegExp</span>.$<span class="number">1</span></span><br><span class="line">             name=name.trim()</span><br><span class="line">             node.nodeValue=vm.data[name]</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<p>然后，在向碎片化文档中添加节点时，每个节点都处理一下。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//碎片化文档，遍历app所有子元素，调用编译函数更新model</span></span><br><span class="line">   <span class="function"><span class="keyword">function</span> <span class="title">nodeTofragment</span>(<span class="params">node,vm</span>) </span>&#123;</span><br><span class="line">       <span class="keyword">let</span> fragment=<span class="built_in">document</span>.createDocumentFragment()</span><br><span class="line">       <span class="keyword">let</span> child</span><br><span class="line">       <span class="keyword">while</span>(child=node.firstChild)&#123;</span><br><span class="line">       	<span class="comment">//添加编译函数</span></span><br><span class="line">           compile(child,vm)</span><br><span class="line">           fragment.appendChild(child)</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">return</span> fragment</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p>创建Vue的实例化函数</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// vue构造函数</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">Vue</span>(<span class="params">options</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">let</span> id=options.el</span><br><span class="line">      <span class="keyword">this</span>.data=options.data</span><br><span class="line">      <span class="keyword">let</span> dom = nodeTofragment(<span class="built_in">document</span>.getElementById(id),<span class="keyword">this</span>)</span><br><span class="line">      <span class="built_in">document</span>.getElementById(id).appendChild(dom)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">var</span> vm=<span class="keyword">new</span> Vue(&#123;</span><br><span class="line">      el:<span class="string">'app'</span>,</span><br><span class="line">      data:&#123;</span><br><span class="line">          text:<span class="string">'hello world'</span></span><br><span class="line">      &#125;</span><br><span class="line">  &#125;)</span><br></pre></td></tr></table></figure>

<p>效果如下图，已经将data中的数据绑定到节点中。</p>
<p><img src="https://upload-images.jianshu.io/upload_images/24590971-ad648c8485f7f2a2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="CUZTOID(R5)~1$9%0DTG0DU.png"></p>
<h5 id="2-任务2-监听input变化view到model"><a href="#2-任务2-监听input变化view到model" class="headerlink" title="2.任务2-监听input变化view到model"></a>2.任务2-监听input变化view到model</h5><p>对于此任务，我们可以通过事件监听器keyup，input等，来获取到最新的value，然后通过<code>Object.defineProperty</code>将获取的最新的value，赋值给实例vm的text，我们把vm实例中的data下的text通过<code>Object.defineProperty</code>设置为访问器属性，这样给vm.text赋值，就触发了set。set函数的作用一个是更新data中的text。<br>首先实现一个响应式监听属性的函数。一旦有赋新值就发生变化。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">defineReactive</span>(<span class="params">vm,key,val</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">Object</span>.defineProperty(vm,key,&#123;</span><br><span class="line">        <span class="keyword">get</span>:function () &#123;</span><br><span class="line">            <span class="keyword">return</span> val</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="keyword">set</span>:function (newVal) &#123;</span><br><span class="line">            <span class="keyword">if</span>(newVal==val)&#123;</span><br><span class="line">                <span class="keyword">return</span></span><br><span class="line">            &#125;</span><br><span class="line">            val=newVal</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后，实现一个观察者，对于一个实例 每一个属性值都进行观察。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//观察者函数</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">observe</span>(<span class="params">obj</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">for</span>(<span class="keyword">let</span> key <span class="keyword">of</span> <span class="built_in">Object</span>.keys(obj))&#123;</span><br><span class="line">          defineReactive(obj,key,obj[key])</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p>改写编译函数，注意由于改成了访问器属性，只要存在复制操作就行触发set，访问的方法也产生变化，同时添加了事件监听器，把实例的text值随时更新。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 编译函数，把data数据更新给model</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">compile</span>(<span class="params">node,vm</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">let</span> attr = node.attributes</span><br><span class="line">      <span class="keyword">if</span>(node.nodeType===<span class="number">1</span>)&#123;</span><br><span class="line">          <span class="keyword">for</span>(<span class="keyword">let</span> i=<span class="number">0</span>;i&lt;attr.length;i++)&#123;</span><br><span class="line">              <span class="keyword">if</span>(attr[i].nodeName==<span class="string">'v-model'</span>)&#123;</span><br><span class="line">                  <span class="keyword">let</span> name = attr[i].nodeValue</span><br><span class="line">                  <span class="comment">//增加时间监听，将结果赋值给data</span></span><br><span class="line">                  node.addEventListener(<span class="string">'input'</span>,<span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span><br><span class="line">                      vm.data[name]=e.target.value</span><br><span class="line">                  &#125;)</span><br><span class="line">                  node.value=vm.data[name]</span><br><span class="line">                  node.removeAttribute(<span class="string">'v-model'</span>)</span><br><span class="line">              &#125;</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">let</span> reg=<span class="regexp">/\&#123;\&#123;(.*)\&#125;\&#125;/</span></span><br><span class="line">      <span class="keyword">if</span>(node.nodeType===<span class="number">3</span>)&#123;</span><br><span class="line">          <span class="keyword">if</span>(reg.test(node.nodeValue))&#123;</span><br><span class="line">              <span class="keyword">let</span> name = <span class="built_in">RegExp</span>.$<span class="number">1</span></span><br><span class="line">              name=name.trim()</span><br><span class="line">              <span class="comment">// node.nodeValue=vm.data[name]</span></span><br><span class="line">              <span class="keyword">new</span> Watcher(vm,node,name)</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p>然后在实例函数中，观察data中的所有属性值，添加observe函数。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// vue构造函数</span></span><br><span class="line">   <span class="function"><span class="keyword">function</span> <span class="title">Vue</span>(<span class="params">options</span>) </span>&#123;</span><br><span class="line">       <span class="keyword">let</span> id=options.el</span><br><span class="line">       <span class="keyword">this</span>.data=options.data</span><br><span class="line">       observe(options.data)</span><br><span class="line">       <span class="keyword">let</span> dom = nodeTofragment(<span class="built_in">document</span>.getElementById(id),<span class="keyword">this</span>)</span><br><span class="line">       <span class="built_in">document</span>.getElementById(id).appendChild(dom)</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p>做到这一步，打印一下结果我们发现，最终我们改变input中的内容能改变data中的数据，但是页面上的数据却没有刷新。接下来就进行下一步</p>
<h5 id="3-任务3-发布订阅model到view"><a href="#3-任务3-发布订阅model到view" class="headerlink" title="3.任务3-发布订阅model到view"></a>3.任务3-发布订阅model到view</h5><p>继续上一个问题 需要我们注意，当我们修改输入框，改变了vm实例的属性，这是1对1的。但是，我们可能在页面中多处用到 data中的属性，这是1对多的。也就是说，改变1个model的值可以改变多个view中的值。<br>这就需要我们引入一个新的知识点：<br><code>订阅/发布者模式</code><br>    订阅发布模式（又称观察者模式）定义了一种一对多的关系，让多个观察者同时监听某一个主题对象，这个主题对象的状态发生改变时就会通知所有观察者对象。</p>
<p>下面这里举个简单的例子，具体的详情可自行寻找资料：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//订阅发布者模式</span></span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">EventEmitter</span> </span>&#123;</span><br><span class="line">      <span class="keyword">constructor</span>()&#123;</span><br><span class="line">          <span class="keyword">this</span>.listener=<span class="built_in">Object</span>.create(<span class="literal">null</span>)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//事件订阅</span></span><br><span class="line">      on=<span class="function">(<span class="params">event,listerner</span>)=&gt;</span>&#123;</span><br><span class="line">          <span class="keyword">if</span>(!event||!listerner)&#123;</span><br><span class="line">              <span class="keyword">return</span></span><br><span class="line">          &#125;</span><br><span class="line">          <span class="keyword">if</span>(<span class="keyword">this</span>.listener[event])&#123;</span><br><span class="line">              <span class="comment">//如果已经存在就存入一个新的</span></span><br><span class="line">              <span class="keyword">this</span>.listener[event].push(listerner)</span><br><span class="line">          &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">              <span class="comment">//没有就创建一个新得</span></span><br><span class="line">              <span class="keyword">this</span>.listener[event]=[listerner]</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//事件发布</span></span><br><span class="line">      emit=<span class="function">(<span class="params">event,...args</span>)=&gt;</span>&#123;</span><br><span class="line">          <span class="keyword">if</span>(!<span class="keyword">this</span>.hasBind(event))&#123;</span><br><span class="line">              <span class="built_in">console</span>.log(<span class="string">`没有监听event&#125;`</span>)</span><br><span class="line">              <span class="keyword">return</span></span><br><span class="line">          &#125;</span><br><span class="line">          <span class="keyword">this</span>.listener[event].forEach(<span class="function"><span class="params">listener</span>=&gt;</span>&#123;</span><br><span class="line">              listener.call(<span class="keyword">this</span>,...args)</span><br><span class="line">          &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//取消订阅</span></span><br><span class="line">      off=<span class="function">(<span class="params">event,listener</span>)=&gt;</span>&#123;</span><br><span class="line">          <span class="keyword">if</span>(!<span class="keyword">this</span>.hasBind(event))&#123;</span><br><span class="line">              <span class="built_in">console</span>.log(<span class="string">`没有订阅<span class="subst">$&#123;event&#125;</span>`</span>)</span><br><span class="line">              <span class="keyword">return</span></span><br><span class="line">          &#125;</span><br><span class="line">          <span class="keyword">if</span>(!listener)&#123;</span><br><span class="line">              <span class="keyword">delete</span> <span class="keyword">this</span>.listener[event]</span><br><span class="line">              <span class="keyword">return</span></span><br><span class="line">          &#125;</span><br><span class="line">          <span class="keyword">this</span>.listener[event]=<span class="keyword">this</span>.listener[event].filter(<span class="function"><span class="params">item</span>=&gt;</span>&#123;</span><br><span class="line">              item!==listener</span><br><span class="line">          &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//事件订阅状态</span></span><br><span class="line">      hasBind=<span class="function"><span class="params">event</span>=&gt;</span>&#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="keyword">this</span>.listener[event]&amp;&amp;</span><br><span class="line">                  <span class="keyword">this</span>.listener[event].length</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">const</span> baseEvent = <span class="keyword">new</span> EventEmitter()</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">cb</span>(<span class="params">value</span>)</span>&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">"hello "</span>+value)</span><br><span class="line">  &#125;</span><br><span class="line">  baseEvent.on(<span class="string">"click"</span>,cb)</span><br><span class="line">  baseEvent.emit(<span class="string">"click"</span>,<span class="string">'2020'</span>) <span class="comment">//打印出“hello 2020”</span></span><br></pre></td></tr></table></figure>

<p>上面的例子只是简单的做个参考，理解其中的意思就行。现在继续正文，在我们的这个实现中，我们需要在<code>Object.defineProperty</code>中的get中订阅我们的事情，在set中发布事件。在编译 HTML 的过程中，会为每个与数据绑定相关的节点生成一个订阅者 watcher，watcher 会将自己添加到相应属性的 dep 容器中。<br>我们已经实现：修改输入框内容 =&gt; 在事件回调函数中修改属性值 =&gt; 触发属性的 set 方法。接下来我们要实现的是：发出通知 dep.notify() =&gt; 触发订阅者的 update 方法 =&gt; 更新视图。这里的关键逻辑是：如何将 watcher 添加到关联属性的 dep 中。<br>    注意： 我把直接赋值的操作改为了 添加一个 Watcher 订阅者</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 编译函数，把data数据更新给model</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">compile</span>(<span class="params">node,vm</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">let</span> attr = node.attributes</span><br><span class="line">      <span class="keyword">if</span>(node.nodeType===<span class="number">1</span>)&#123;</span><br><span class="line">          <span class="keyword">for</span>(<span class="keyword">let</span> i=<span class="number">0</span>;i&lt;attr.length;i++)&#123;</span><br><span class="line">              <span class="keyword">if</span>(attr[i].nodeName==<span class="string">'v-model'</span>)&#123;</span><br><span class="line">                  <span class="keyword">let</span> name = attr[i].nodeValue</span><br><span class="line">                  node.addEventListener(<span class="string">'input'</span>,<span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span><br><span class="line">                      vm.data[name]=e.target.value</span><br><span class="line">                  &#125;)</span><br><span class="line">                  node.value=vm.data[name]</span><br><span class="line">                  node.removeAttribute(<span class="string">'v-model'</span>)</span><br><span class="line">              &#125;</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">let</span> reg=<span class="regexp">/\&#123;\&#123;(.*)\&#125;\&#125;/</span></span><br><span class="line">      <span class="keyword">if</span>(node.nodeType===<span class="number">3</span>)&#123;</span><br><span class="line">          <span class="keyword">if</span>(reg.test(node.nodeValue))&#123;</span><br><span class="line">              <span class="keyword">let</span> name = <span class="built_in">RegExp</span>.$<span class="number">1</span></span><br><span class="line">              name=name.trim()</span><br><span class="line">              <span class="comment">// node.nodeValue=vm.data[name]</span></span><br><span class="line">              <span class="keyword">new</span> Watcher(vm,node,name) <span class="comment">//这里创建了一个订阅者</span></span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p>然后就是写一个订阅者函数</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Watcher</span>(<span class="params">vm,node,name</span>) </span>&#123;</span><br><span class="line">       Dep.target=<span class="keyword">this</span></span><br><span class="line">       <span class="keyword">this</span>.vm=vm</span><br><span class="line">       <span class="keyword">this</span>.node=node</span><br><span class="line">       <span class="keyword">this</span>.name=name</span><br><span class="line">       <span class="keyword">this</span>.update()</span><br><span class="line">   &#125;</span><br><span class="line">   Watcher.prototype=&#123;</span><br><span class="line">       <span class="keyword">get</span>:function () &#123;</span><br><span class="line">           <span class="keyword">this</span>.value=<span class="keyword">this</span>.vm.data[<span class="keyword">this</span>.name]</span><br><span class="line">       &#125;,</span><br><span class="line">       update:<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">           <span class="keyword">this</span>.get()</span><br><span class="line">           <span class="keyword">this</span>.node.nodeValue=<span class="keyword">this</span>.value</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p>首先，将自己赋给了一个全局变量<code>Dep.target</code>；</p>
<p>其次，执行了 update 方法，进而执行了 get 方法，get 的方法读取了 vm 的访问器属性，从而触发了访问器属性的 get 方法，get 方法中将该 watcher 添加到了对应访问器属性的 dep 中；</p>
<p>再次，获取属性的值，然后更新视图。</p>
<p>最后，将 <code>Dep.target</code>设为空。因为它是全局变量，也是 watcher 与 dep 关联的唯一桥梁，任何时刻都必须保证<code>Dep.target</code> 只有一个值。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">defineReactive</span>(<span class="params">vm,key,val</span>) </span>&#123;</span><br><span class="line">       <span class="keyword">var</span> dep=<span class="keyword">new</span> Dep()</span><br><span class="line">       <span class="built_in">Object</span>.defineProperty(vm,key,&#123;</span><br><span class="line">           <span class="keyword">get</span>:function () &#123;</span><br><span class="line">               <span class="comment">// 在这里进行订阅操作</span></span><br><span class="line">               <span class="keyword">if</span>(Dep.target) &#123;</span><br><span class="line">                   <span class="built_in">console</span>.log(Dep.target)</span><br><span class="line">                  dep.on(Dep.target)</span><br><span class="line">               &#125;</span><br><span class="line">               <span class="keyword">return</span> val</span><br><span class="line">           &#125;,</span><br><span class="line">           <span class="keyword">set</span>:function (newVal) &#123;</span><br><span class="line">               <span class="keyword">if</span>(newVal==val)&#123;</span><br><span class="line">                   <span class="keyword">return</span></span><br><span class="line">               &#125;</span><br><span class="line">               val=newVal</span><br><span class="line">               dep.emit()</span><br><span class="line">               <span class="built_in">console</span>.log(<span class="string">'新值'</span>+newVal)</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;)</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p>然后写一个订阅者发布者构造函数。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Dep</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.listener=[]</span><br><span class="line">    &#125;</span><br><span class="line">    Dep.prototype=&#123;</span><br><span class="line">        on:<span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.listener.push(event)</span><br><span class="line">        &#125;,</span><br><span class="line">        emit:<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.listener.forEach(<span class="function"><span class="params">event</span>=&gt;</span>&#123;</span><br><span class="line">                event.update()</span><br><span class="line">            &#125;)</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>到这里基本就实现了vue的双向绑定，有点繁琐，写的也有点复杂。在这里进行记录一下，下面给上全部代码。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">    &lt;title&gt;Title&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">&lt;div id=<span class="string">"app"</span>&gt;</span><br><span class="line">    &lt;input type=<span class="string">"text"</span>  v-model=<span class="string">"text"</span>&gt;&#123;&#123;text&#125;&#125;</span><br><span class="line">&lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">&lt;script&gt;</span></span><br><span class="line"><span class="regexp">    function defineReactive(vm,key,val) &#123;</span></span><br><span class="line"><span class="regexp">        var dep=new Dep()</span></span><br><span class="line"><span class="regexp">        Object.defineProperty(vm,key,&#123;</span></span><br><span class="line"><span class="regexp">            get:function () &#123;</span></span><br><span class="line"><span class="regexp">                if(Dep.target) &#123;</span></span><br><span class="line"><span class="regexp">                    console.log(Dep.target)</span></span><br><span class="line"><span class="regexp">                   dep.on(Dep.target)</span></span><br><span class="line"><span class="regexp">                &#125;</span></span><br><span class="line"><span class="regexp">                return val</span></span><br><span class="line"><span class="regexp">            &#125;,</span></span><br><span class="line"><span class="regexp">            set:function (newVal) &#123;</span></span><br><span class="line"><span class="regexp">                if(newVal==val)&#123;</span></span><br><span class="line"><span class="regexp">                    return</span></span><br><span class="line"><span class="regexp">                &#125;</span></span><br><span class="line"><span class="regexp">                val=newVal</span></span><br><span class="line"><span class="regexp">                dep.emit()</span></span><br><span class="line"><span class="regexp">                console.log('新值'+newVal)</span></span><br><span class="line"><span class="regexp">            &#125;</span></span><br><span class="line"><span class="regexp">        &#125;)</span></span><br><span class="line"><span class="regexp">    &#125;</span></span><br><span class="line"><span class="regexp">    /</span><span class="regexp">/观察者函数</span></span><br><span class="line"><span class="regexp">    function observe(obj) &#123;</span></span><br><span class="line"><span class="regexp">        for(let key of Object.keys(obj))&#123;</span></span><br><span class="line"><span class="regexp">            defineReactive(obj,key,obj[key])</span></span><br><span class="line"><span class="regexp">        &#125;</span></span><br><span class="line"><span class="regexp">    &#125;</span></span><br><span class="line"><span class="regexp">    /</span><span class="regexp">/ 编译函数，把data数据更新给model</span></span><br><span class="line"><span class="regexp">    function compile(node,vm) &#123;</span></span><br><span class="line"><span class="regexp">        let attr = node.attributes</span></span><br><span class="line"><span class="regexp">        if(node.nodeType===1)&#123;</span></span><br><span class="line"><span class="regexp">            for(let i=0;i&lt;attr.length;i++)&#123;</span></span><br><span class="line"><span class="regexp">                if(attr[i].nodeName=='v-model')&#123;</span></span><br><span class="line"><span class="regexp">                    let name = attr[i].nodeValue</span></span><br><span class="line"><span class="regexp">                    node.addEventListener('input',function (e) &#123;</span></span><br><span class="line"><span class="regexp">                        vm.data[name]=e.target.value</span></span><br><span class="line"><span class="regexp">                    &#125;)</span></span><br><span class="line"><span class="regexp">                    node.value=vm.data[name]</span></span><br><span class="line"><span class="regexp">                    node.removeAttribute('v-model')</span></span><br><span class="line"><span class="regexp">                &#125;</span></span><br><span class="line"><span class="regexp">            &#125;</span></span><br><span class="line"><span class="regexp">        &#125;</span></span><br><span class="line"><span class="regexp">        let reg=/</span>\&#123;\&#123;(.*)\&#125;\&#125;/</span><br><span class="line">        <span class="keyword">if</span>(node.nodeType===<span class="number">3</span>)&#123;</span><br><span class="line">            <span class="keyword">if</span>(reg.test(node.nodeValue))&#123;</span><br><span class="line">                <span class="keyword">let</span> name = <span class="built_in">RegExp</span>.$<span class="number">1</span></span><br><span class="line">                name=name.trim()</span><br><span class="line">                <span class="comment">// node.nodeValue=vm.data[name]</span></span><br><span class="line">                <span class="keyword">new</span> Watcher(vm,node,name)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">Dep</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.listener=[]</span><br><span class="line">    &#125;</span><br><span class="line">    Dep.prototype=&#123;</span><br><span class="line">        on:<span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.listener.push(event)</span><br><span class="line">        &#125;,</span><br><span class="line">        emit:<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.listener.forEach(<span class="function"><span class="params">event</span>=&gt;</span>&#123;</span><br><span class="line">                event.update()</span><br><span class="line">            &#125;)</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">Watcher</span>(<span class="params">vm,node,name</span>) </span>&#123;</span><br><span class="line">        Dep.target=<span class="keyword">this</span></span><br><span class="line">        <span class="keyword">this</span>.vm=vm</span><br><span class="line">        <span class="keyword">this</span>.node=node</span><br><span class="line">        <span class="keyword">this</span>.name=name</span><br><span class="line">        <span class="keyword">this</span>.update()</span><br><span class="line">    &#125;</span><br><span class="line">    Watcher.prototype=&#123;</span><br><span class="line">        <span class="keyword">get</span>:function () &#123;</span><br><span class="line">            <span class="keyword">this</span>.value=<span class="keyword">this</span>.vm.data[<span class="keyword">this</span>.name]</span><br><span class="line">        &#125;,</span><br><span class="line">        update:<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.get()</span><br><span class="line">            <span class="keyword">this</span>.node.nodeValue=<span class="keyword">this</span>.value</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//碎片化文档，遍历app所有子元素，调用编译函数更新model</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">nodeTofragment</span>(<span class="params">node,vm</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">let</span> fragment=<span class="built_in">document</span>.createDocumentFragment()</span><br><span class="line">        <span class="keyword">let</span> child</span><br><span class="line">        <span class="keyword">while</span>(child=node.firstChild)&#123;</span><br><span class="line">            compile(child,vm)</span><br><span class="line">            fragment.appendChild(child)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> fragment</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// vue构造函数</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">Vue</span>(<span class="params">options</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">let</span> id=options.el</span><br><span class="line">        <span class="keyword">this</span>.data=options.data</span><br><span class="line">        observe(options.data)</span><br><span class="line">        <span class="keyword">let</span> dom = nodeTofragment(<span class="built_in">document</span>.getElementById(id),<span class="keyword">this</span>)</span><br><span class="line">        <span class="built_in">document</span>.getElementById(id).appendChild(dom)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> vm=<span class="keyword">new</span> Vue(&#123;</span><br><span class="line">        el:<span class="string">'app'</span>,</span><br><span class="line">        data:&#123;</span><br><span class="line">            text:<span class="string">'hello world'</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line">&lt;<span class="regexp">/html&gt;</span></span><br></pre></td></tr></table></figure>

<hr>
<p>本文到底就结束啦~</p>

      
    </div>
    
    
    

    

    

    
    <div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

  
</div>
    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Vue/" rel="tag"><i class="fa fa-tag"></i>  Vue</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/11/16/Vue项目中列表组件的key的作用/" rel="next" title="Vue项目中列表组件中写key的作用">
                <i class="fa fa-chevron-left"></i> Vue项目中列表组件中写key的作用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="http://tva2.sinaimg.cn/crop.0.0.768.768.1024/6cc1c2cfjw8eh3kv8yvs9j20lc0lcdgl.jpg" alt="YauCheun">
            
              <p class="site-author-name" itemprop="name">YauCheun</p>
              <p class="site-description motion-element" itemprop="description">YauCheun</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/YauCheun" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:yaucheung@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/YauCheun" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-crosshairs"></i>CSDN</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-前言"><span class="nav-number">1.</span> <span class="nav-text">1.前言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-思路分析"><span class="nav-number">2.</span> <span class="nav-text">2.思路分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-原理"><span class="nav-number">3.</span> <span class="nav-text">3.原理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-具体实现"><span class="nav-number">4.</span> <span class="nav-text">4.具体实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-实现效果"><span class="nav-number">4.1.</span> <span class="nav-text">1.实现效果</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-任务拆分"><span class="nav-number">4.2.</span> <span class="nav-text">2.任务拆分</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-分布执行任务"><span class="nav-number">4.3.</span> <span class="nav-text">3.分布执行任务</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-任务1-绑定data到view"><span class="nav-number">4.3.1.</span> <span class="nav-text">1.任务1-绑定data到view</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-任务2-监听input变化view到model"><span class="nav-number">4.3.2.</span> <span class="nav-text">2.任务2-监听input变化view到model</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-任务3-发布订阅model到view"><span class="nav-number">4.3.3.</span> <span class="nav-text">3.任务3-发布订阅model到view</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-[object Object]"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">YauCheun</span>

  
</div>


   <div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span> 

<i class="fa fa-eye"></i>
<span id="busuanzi_container_site_pv">
    本站总访问量:<span id="busuanzi_value_site_pv"></span>次
</span>
</div>
 









<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共31.4k字</span>
</div>
        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>

</body>
</html>
